import React, { useState } from 'react';
import { PersonData } from '@/types/aiPerson';

interface CharacterProfilesFormProps {
  data: PersonData;
  onChange: (data: PersonData) => void;
}

// 角色设定表单组件
const CharacterProfilesForm: React.FC<CharacterProfilesFormProps> = ({ data, onChange }) => {
  const [isDragOver, setIsDragOver] = useState(false); // 拖拽状态

  // 处理表单字段变化
  const handleFieldChange = (field: string, value: any) => {
    if (field.startsWith('character_profiles.voice_settings.')) {
      // 处理嵌套的 voice_settings 字段
      const voiceField = field.replace('character_profiles.voice_settings.', '');
      onChange({
        ...data,
        character_profiles: {
          ...data.character_profiles,
          voice_settings: {
            ...data.character_profiles.voice_settings,
            [voiceField]: value
          }
        }
      });
    } else if (field.startsWith('character_profiles.')) {
      // 处理 character_profiles 字段
      const profileField = field.replace('character_profiles.', '');
      onChange({
        ...data,
        character_profiles: {
          ...data.character_profiles,
          [profileField]: value
        }
      });
    }
  };

  // 处理输入框变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    handleFieldChange(name, value);
  };

  // 处理textarea自动调整高度
  const handleTextareaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    // 自动调整高度
    e.target.style.height = 'auto';
    e.target.style.height = e.target.scrollHeight + 'px';
    
    handleFieldChange(name, value);
  };

  // 处理emotions_list数组变化
  const handleEmotionChange = (idx: number, field: 'name' | 'path' | 'prompt_text', value: string) => {
    const newEmotionsList = data.character_profiles.Emotions.Emotions_list.map((item, i) =>
      i === idx ? { ...item, [field]: value } : item
    );
    
    onChange({
      ...data,
      character_profiles: {
        ...data.character_profiles,
        Emotions: {
          ...data.character_profiles.Emotions,
          Emotions_list: newEmotionsList
        }
      }
    });
  };

  // 添加emotion项
  const addEmotion = () => {
    const newEmotionsList = [...data.character_profiles.Emotions.Emotions_list, { name: "", path: "", prompt_text: "" }];
    onChange({
      ...data,
      character_profiles: {
        ...data.character_profiles,
        Emotions: {
          ...data.character_profiles.Emotions,
          Emotions_list: newEmotionsList
        }
      }
    });
  };

  // 删除emotion项
  const removeEmotion = (idx: number) => {
    const newEmotionsList = data.character_profiles.Emotions.Emotions_list.filter((_, i) => i !== idx);
    onChange({
      ...data,
      character_profiles: {
        ...data.character_profiles,
        Emotions: {
          ...data.character_profiles.Emotions,
          Emotions_list: newEmotionsList
        }
      }
    });
  };

  // 验证文件类型
  const validateFile = (file: File) => {
    const allowedTypes = ['text/plain', 'text/markdown', 'application/x-markdown'];
    const isMarkdown = file.name.endsWith('.md') || file.name.endsWith('.markdown');

    if (!allowedTypes.includes(file.type) && !isMarkdown) {
      return false;
    }
    return true;
  };

  // 处理文件读取
  const processFile = (file: File) => {
    if (!validateFile(file)) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target?.result as string;
      // 将文件内容填充到角色提示词输入框
      handleFieldChange('character_profiles.promptWord', content);

      // 延迟调整textarea高度，确保内容已更新
      setTimeout(() => {
        const textarea = document.querySelector('textarea[name="character_profiles.promptWord"]') as HTMLTextAreaElement;
        if (textarea) {
          textarea.style.height = 'auto';
          textarea.style.height = textarea.scrollHeight + 'px';
        }
      }, 0);
    };
    reader.readAsText(file);
  };

  // 处理文件上传 (text/markdown)
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    processFile(file);
  };

  // 处理拖拽进入
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(true);
  };

  // 处理拖拽离开
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);
  };

  // 处理拖拽悬停
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };

  // 处理文件拖拽放下
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOver(false);

    const files = e.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0];
      processFile(file);
    }
  };

  return (
    <div>
      <h3 className="text-xl font-semibold text-gray-800 mb-6 border-b pb-2">角色设定</h3>

      <fieldset className="border border-gray-300 rounded-xl p-6 mb-6">
        <legend className="px-2 text-blue-600 font-medium">Character Profiles</legend>

        {/* 角色提示词编辑器 */}
        <div className="mb-6">
          <label className="block mb-2 font-medium text-gray-700">角色提示词（PromptWord）</label>
          <textarea
            name="character_profiles.promptWord"
            value={data.character_profiles.promptWord}
            onChange={handleTextareaChange}
            placeholder="请输入角色的详细描述和提示词..."
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm resize-none overflow-hidden"
            style={{ minHeight: '120px' }}
          />
        </div>

        {/* 文件上传区域 */}
        <div className="mb-6">
          <label className="block mb-2 font-medium text-gray-700">上传文本文件（支持 .txt 或 .md 格式）</label>
          <div
            className={`border-2 border-dashed rounded-lg p-6 transition-all ${isDragOver
              ? 'border-blue-400 bg-blue-50'
              : 'border-gray-300 hover:border-gray-400'
              }`}
            onDragEnter={handleDragEnter}
            onDragLeave={handleDragLeave}
            onDragOver={handleDragOver}
            onDrop={handleDrop}
          >
            <div className="text-center">
              <div className="mb-4">
                <svg
                  className={`mx-auto h-12 w-12 ${isDragOver ? 'text-blue-400' : 'text-gray-400'}`}
                  stroke="currentColor"
                  fill="none"
                  viewBox="0 0 48 48"
                >
                  <path
                    d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                    strokeWidth={2}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </div>
              <div className="mb-4">
                <label htmlFor="file-upload" className="cursor-pointer">
                  <span className={`text-sm font-medium ${isDragOver ? 'text-blue-600' : 'text-blue-600 hover:text-blue-500'}`}>
                    点击上传文件
                  </span>
                  <input
                    id="file-upload"
                    type="file"
                    accept=".txt,.md,.markdown,text/plain,text/markdown"
                    onChange={handleFileUpload}
                    className="sr-only"
                  />
                </label>
                <span className="text-sm text-gray-500"> 或拖拽文件到此处</span>
              </div>
              <p className="text-xs text-gray-500">
                支持 TXT 和 Markdown 格式，文件内容将自动填充到角色提示词输入框
              </p>
              {isDragOver && (
                <p className="text-xs text-blue-600 mt-2 font-medium">
                  松开鼠标即可上传文件
                </p>
              )}
            </div>
          </div>
        </div>

        {/* 声音设置 */}
        <div className="mb-6">
          <label className="block mb-2 font-medium text-gray-700">声音设置</label>
          <div className="pl-4 border-l-2 border-blue-200 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
              <label className="block mb-1 text-sm text-gray-600">GPT路径</label>
              <input
                name="character_profiles.voice_settings.gpt_path"
                value={data.character_profiles.voice_settings.gpt_path}
                onChange={handleInputChange}
                placeholder="GPT权重路径"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block mb-1 text-sm text-gray-600">SoVITS路径</label>
              <input
                name="character_profiles.voice_settings.sovits_path"
                value={data.character_profiles.voice_settings.sovits_path}
                onChange={handleInputChange}
                placeholder="SoVITS权重路径"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block mb-1 text-sm text-gray-600">参考音频路径</label>
              <input
                name="character_profiles.voice_settings.refer_wav_path"
                value={data.character_profiles.voice_settings.refer_wav_path}
                onChange={handleInputChange}
                placeholder="参考音频路径"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block mb-1 text-sm text-gray-600">文本语言</label>
              <select
                name="character_profiles.voice_settings.text_language"
                value={data.character_profiles.voice_settings.text_language}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="ja">日语</option>
                <option value="en">英语</option>
                <option value="zh">中文</option>
              </select>
            </div>
            <div>
              <label className="block mb-1 text-sm text-gray-600">提示词语言</label>
              <select
                name="character_profiles.voice_settings.prompt_language"
                value={data.character_profiles.voice_settings.prompt_language}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="ja">日语</option>
                <option value="en">英语</option>
                <option value="zh">中文</option>
              </select>
            </div>
          </div>
        </div>

        {/* 情感配置 */}
        <div className="mb-6">
          <label className="block mb-2 font-medium text-gray-700">情感配置</label>
          <div className="pl-4 border-l-2 border-blue-200">
            {data.character_profiles.Emotions.Emotions_list.map((item, idx) => (
              <div key={idx} className="mb-4 p-4 border border-gray-200 rounded-lg">
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div>
                    <label className="block mb-1 text-sm text-gray-600">情感名称</label>
                    <input
                      value={item.name}
                      onChange={e => handleEmotionChange(idx, 'name', e.target.value)}
                      placeholder="如：default, smile, happy"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block mb-1 text-sm text-gray-600">音频路径</label>
                    <input
                      value={item.path}
                      onChange={e => handleEmotionChange(idx, 'path', e.target.value)}
                      placeholder="如：Voice/Ref/001-默认.wav"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                  <div>
                    <label className="block mb-1 text-sm text-gray-600">提示词文本</label>
                    <textarea
                      value={item.prompt_text}
                      onChange={e => handleEmotionChange(idx, 'prompt_text', e.target.value)}
                      placeholder="情感对应的提示词文本"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                      rows={2}
                    />
                  </div>
                </div>
                <div className="mt-2 flex justify-end">
                  <button
                    type="button"
                    className="px-3 py-1 text-red-600 border border-red-300 rounded-lg hover:bg-red-50 transition-all text-sm"
                    onClick={() => removeEmotion(idx)}
                    disabled={data.character_profiles.Emotions.Emotions_list.length === 1}
                  >
                    删除情感
                  </button>
                </div>
              </div>
            ))}
            <button
              type="button"
              className="px-4 py-2 text-blue-600 border border-blue-300 rounded-lg hover:bg-blue-50 transition-all"
              onClick={addEmotion}
            >
              添加情感
            </button>
          </div>
        </div>

        {/* 图片模型 */}
        <div className="mb-6">
          <label className="block mb-2 font-medium text-gray-700">图片模型</label>
          <select
            name="character_profiles.work_flow"
            value={data.character_profiles.work_flow}
            onChange={handleInputChange}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="AS1-G001">AS1-G001</option>
            <option value="AS1">AS1</option>
            <option value="AS2">AS2</option>
            <option value="AS3">AS3</option>
          </select>
        </div>

        {/* 角色图片提示词 */}
        <div className="mb-6">
          <label className="block mb-2 font-medium text-gray-700">角色图片提示词</label>
          <textarea
            name="character_profiles.persionImageDescription"
            value={data.character_profiles.persionImageDescription}
            onChange={handleTextareaChange}
            placeholder="请输入角色图片生成的提示词..."
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none overflow-hidden"
            style={{ minHeight: '60px' }}
          />
        </div>
      </fieldset>
    </div>
  );
};

export default CharacterProfilesForm;